<template>
  <div>
    <ZgDialog title="查看" width="60%" v-model="showHtmlDialog" :showFooter="false">
      <div class="wfull flx-c">
        <div class="wfull rich-text" v-html="html">
        </div>
      </div>
    </ZgDialog>
    <Add :formCode="formCode" ref="add" @ok="search"></Add>
    <Update :formCode="formCode" ref="update" @ok="search"></Update>
    <Batch :formCode="formCode" ref="batch" @ok="search"></Batch>
    <ZgAttach
      ref="attach"
      :showBtn="false"
      :tableName="formCode"></ZgAttach>
    <ZgDataImport
      ref="import"
      :showBtn="false"
      :fileName="`${formCode}.xlsx`"
      :url="importUrl"
      @ok="search"></ZgDataImport>
    <ZgNewPage
      ref="page"
      :title="title"
      addBtnName="添加数据"
      :uniqueName="formCode"
      :pageOpt="pageOpt"
      :batchBtns="batchBtns"
      :dataBtns="dataBtns"
      :headers="backHeaders"
      :conditions="conditions"
      @search="onSearch"
      @filter="onFilter"
      @header="mergeHeader"
      @add="toAdd"
      @batch="toBatch"
      @admin="toAdmin"
    >
      <template slot="columns">
        <a-table-column
          v-for="(h,i) in headers"
          :key="`column${i}`"
          :width="h.width===0 ? 'auto' : h.width"
          :title="h.label">
          <template slot-scope="record">
            <div v-if="headers[i].type==='多行文本'">
              <a-popover>
                <template #content>
                  {{ record[h.code] }}
                </template>
                <span>
                  {{ record[h.code].length>10?(record[h.code].substring(0,10)+'...'):record[h.code] }}
                </span>
              </a-popover>
            </div>
            <div v-else-if="headers[i].type==='富文本'"><a @click="showHtml(record[h.code])">查看</a></div>
            <div v-else-if="headers[i].type==='图片'">
              <ZgImgHolder :width="48" :height="48" :src="record[h.code]"/>
            </div>
            <div v-else-if="headers[i].type==='字典'">
              <ZgDicHolder :code="record[h.code]" :parentCode="headers[i].extra.字典类型"/>
            </div>
            <div v-else-if="headers[i].type==='多选'">
              <ZgDicHolder
                v-for="(x,j) in record[h.code].split(',')"
                :key="`${h.code}_mlt_${j}`"
                :code="x"
                :parentCode="headers[i].extra.字典类型"/>
            </div>
            <div v-else-if="['单选框','开关'].includes(headers[i].type)">
              <a-tag>{{ (record[h.code]===1||record[h.code]===true)?'是':'否' }}</a-tag>
            </div>
            <div v-else>
              {{ record[h.code] }}
            </div>
          </template>
        </a-table-column>
      </template>
      <template slot="thMode" slot-scope="scope">
        <a-row :gutter="10">
          <a-col :span="4" v-for="t in scope.list" :key="`thMode_${t.id}`">
            <a-card class="mb10">
              <div class="wfull h100 scroll">
                {{ t }}
              </div>
            </a-card>
          </a-col>
        </a-row>
      </template>
    </ZgNewPage>
  </div>
</template>
<script>
import Add from './Add'
import Update from './Update'
import Batch from './Batch'
export default {
  components: {
    Add, Update, Batch
  },
  props: {
    title: {
      type: String,
      default: '动态表单'
    },
    formCode: {
      type: String,
      default: 'form_test'
    },
    importUrl: {
      type: String,
      default: ''
    },
    exportUrl: {
      type: String,
      default: ''
    },
    exportName: {
      type: String,
      default: '导出数据'
    }
  },
  data () {
    return {
      html: '',
      showHtmlDialog: false,
      pageOpt: {
        showConditionBtn: true,
        showHeaderConfig: true,
        showAttachBtn: true
      },
      headers: [],
      backHeaders: [],
      conditions: [],
      batchBtns: [
        { key: 1, label: '批量删除' },
        { key: 2, label: '批量修改' },
        { key: 3, label: 'Excel导入' },
        { key: 4, label: 'Excel导出' }
      ],
      dataBtns: [
        { key: 1, name: '删除', type: 'link', icon: 'fa-trash', isShow: () => { return true } },
        { key: 2, name: '修改', type: 'link', icon: 'fa-pencil', isShow: () => { return true } },
        { key: 3, name: '附件', type: 'link', icon: 'fa-file', isShow: () => { return true } }
      ],
      attTypeArr: [
        { name: '附件1', type: '.png', limit: 10 },
        { name: '附件2', type: '.xlsx', limit: 10 }
      ]
    }
  },
  mounted () {
    this.searchColumn()
    this.searchCondition()
  },
  methods: {
    // 分页数据查询
    search () {
      this.$refs.page.search()
    },
    // 查询条件
    searchCondition () {
      this.$http.get('/zg-autoform/zxb/condition/view', {
        formCode: this.formCode
      }, data => {
        this.conditions = data.map(t => {
          return {
            code: t.alias,
            compType: t.columnType,
            label: t.label,
            extra: JSON.parse(t.extra),
            defaultVal: ['整数', '浮点数'].includes(t.columnType) ? 0 : ''
          }
        })
      })
    },
    // 查询表头信息
    searchColumn () {
      this.$http.get('/zg-autoform/zxb/form/column', {
        formCode: this.formCode
      }, data => {
        this.headers = data.map(t => {
          return {
            code: t.code,
            label: t.name,
            type: t.compType,
            extra: JSON.parse(t.extra),
            width: 0,
            isShow: true,
            sort: t.sort
          }
        })
        this.backHeaders = JSON.parse(JSON.stringify(this.headers))
      })
    },
    onSearch (param) {
      // 读取用户个性化表头数据
      const diyHeaderKey = this.currentUser.username + '_diyHeader_' + this.formCode
      const diyHeaders = localStorage.getItem(diyHeaderKey)
      if (diyHeaders) {
        this.mergeHeader(JSON.parse(diyHeaders))
      }
      // 加载数据
      this.$http.post('/zg-autoform/zxb/table/data/page/' + this.formCode, param, data => {
        this.$refs.page.endSearch(
          {
            total: data[0],
            list: data[1].map(t => {
              const result = {
                key: t.ID
              }
              for (const key in t) {
                result[key.toLowerCase()] = t[key]
              }
              return result
            })
          }
        )
      })
    },
    onFilter (f, param) {
    },
    toAdd () {
      this.$refs.add.open()
    },
    toAdmin (param) {
      if (param.key === 1) {
        this.confirm(
        () => {
          this.$http.post('/zg-autoform/zxb/table/data/del/' + this.formCode, [param.obj.id], () => {
            this.search()
          })
        },
        '确定要删除这条数据么')
      } else if (param.key === 2) {
        this.$refs.update.open(param.obj)
      } else if (param.key === 3) {
        this.$refs.attach.open(param.obj)
      }
    },
    toBatch (opt) {
      if (opt.key === 1) {
        this.$refs.page.checkIds(ids => {
          this.$http.post('/zg-autoform/zxb/table/data/del/' + this.formCode, ids, () => {
            this.search()
          })
        }, '确定要批量删除这些数据')
      } else if (opt.key === 2) {
        this.$refs.page.checkIds(ids => {
          this.$refs.batch.open(ids)
        }, '确定要批量修改这些数据')
      } else if (opt.key === 3) {
        this.$refs.import.open()
      } else if (opt.key === 4) {
        if (this.exportUrl.length === 0) {
          this.$error({ title: '请设置导出接口' })
          return
        }
        this.$http.download(this.exportUrl, {}, `${this.exportName}.xlsx`)
      }
    },
    mergeHeader (newHeaders) {
      if (!newHeaders) {
        return
      }
      this.headers = newHeaders.filter(t => {
        return t.isShow
      }).sort((a, b) => {
        return a.sort - b.sort
      })
    },
    showHtml (content) {
      this.html = content
      this.showHtmlDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
